﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ImpromptuInterface.Dynamic;

namespace TestSilverlightApp
{
    public class MainPageVm:ImpromptuInterface.MVVM.ImpromptuViewModel<MainPageVm.IContract>
    {

        public interface IContract
        {
            DateTime StartDate { get; set; }
            DateTime EndDate { get; set; }
            int Limit { get; set; }
            double Progress { get; set; }
            BackgroundWorker BackgroundWorker { get; set; }
        }

        public MainPageVm()
        {
            Contract.StartDate = DateTime.Today.AddMonths(-3);
            Contract.EndDate = DateTime.Today;
            Contract.Limit = 4;
            Contract.Progress = 0d;
            Dynamic.Data = null;

            PropertyChanged += (sender, e) => Command.Search.RaiseCanExecuteChanged();

            Contract.BackgroundWorker  = new BackgroundWorker();
            Contract.BackgroundWorker.WorkerReportsProgress = true;

            Contract.BackgroundWorker.DoWork += DoWork;

            Contract.BackgroundWorker.ProgressChanged += (sender, e) => Contract.Progress = e.ProgressPercentage;

            Contract.BackgroundWorker.RunWorkerCompleted += (sender, e) => Dynamic.Data= e.Result;
        }


        private void DoWork(dynamic sender, DoWorkEventArgs e)
        {
            dynamic arguments = e.Argument;
            var tList = new List<dynamic>();
            for (int i=0; i < arguments.Limit; i++)
            {
                tList.Add(Build.NewObject(Name:"John Smith", Something:"Else", Index:i));
            }
            e.Result = tList; 
            sender.ReportProgress(100);

        }


        public void Search(object parameter)
        {

            Dynamic.Data = null; 
            Contract.Progress = 0d;

            Contract.BackgroundWorker.RunWorkerAsync(new { Contract.StartDate, Contract.EndDate, Contract.Limit });
        }
    }
}
